package com.ruoyi.system.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.dto.XsOrderRefundImportDto;
import com.ruoyi.system.domain.xs.XsOrderRefund;
import com.ruoyi.system.service.IXsStoreService;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.XsOrderRefundMapper;
import com.ruoyi.system.service.IXsOrderRefundService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * 订单退款信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-03-06
 */
@Service
public class XsOrderRefundServiceImpl
        extends ServiceImpl<XsOrderRefundMapper, XsOrderRefund>
        implements IXsOrderRefundService {

    @Autowired
    private XsOrderRefundMapper xsOrderRefundMapper;

    @Autowired
    private IXsStoreService xsStoreService;

    private ThreadPoolTaskExecutor taskExecutor = SpringUtils.getBean("threadPoolTaskExecutor");

    /**
     * 查询订单退款信息
     * 
     * @param id 订单退款信息主键
     * @return 订单退款信息
     */
    @Override
    public XsOrderRefund selectXsOrderRefundById(Long id)
    {
        return xsOrderRefundMapper.selectXsOrderRefundById(id);
    }

    /**
     * 查询订单退款信息列表
     * 
     * @param xsOrderRefund 订单退款信息
     * @return 订单退款信息
     */
    @Override
    public List<XsOrderRefund> selectXsOrderRefundList(XsOrderRefund xsOrderRefund)
    {
        return xsOrderRefundMapper.selectXsOrderRefundList(xsOrderRefund);
    }

    /**
     * 新增订单退款信息
     * 
     * @param xsOrderRefund 订单退款信息
     * @return 结果
     */
    @Override
    public int insertXsOrderRefund(XsOrderRefund xsOrderRefund)
    {
        return xsOrderRefundMapper.insertXsOrderRefund(xsOrderRefund);
    }

    /**
     * 修改订单退款信息
     * 
     * @param xsOrderRefund 订单退款信息
     * @return 结果
     */
    @Override
    public int updateXsOrderRefund(XsOrderRefund xsOrderRefund)
    {
        return xsOrderRefundMapper.updateXsOrderRefund(xsOrderRefund);
    }

    /**
     * 批量删除订单退款信息
     * 
     * @param ids 需要删除的订单退款信息主键
     * @return 结果
     */
    @Override
    public int deleteXsOrderRefundByIds(Long[] ids)
    {
        return xsOrderRefundMapper.deleteXsOrderRefundByIds(ids);
    }

    /**
     * 删除订单退款信息信息
     * 
     * @param id 订单退款信息主键
     * @return 结果
     */
    @Override
    public int deleteXsOrderRefundById(Long id)
    {
        return xsOrderRefundMapper.deleteXsOrderRefundById(id);
    }

    /**
     * 导入退款数据
     * @param file
     */
    @Override
    @Transactional
    public void importRefundOrder(MultipartFile file) {
        ExcelUtil<XsOrderRefundImportDto> util = new ExcelUtil<>(XsOrderRefundImportDto.class);
        if (file.isEmpty()) {
            throw new GlobalException("上传的文件为空");
        }
        int count = 2;

        String orderId = null;
        try (InputStream inputStream = file.getInputStream()) {

            Workbook workbook = WorkbookFactory.create(inputStream);

           // Workbook workbook = new XSSFWorkbook(inputStream); // 支持.xlsx格式的Excel文件
            // 表存在数据
            List<XsOrderRefund> exist = new ArrayList<>();
            // 表不存在数据
            List<XsOrderRefund> nonentity = new ArrayList<>();
            // 查询全部订单
            List<XsOrderRefund> orderRefundList = this.lambdaQuery().list();

            Map<String, String> map = new HashMap<>();
            xsStoreService.lambdaQuery().list().forEach(store -> {
                map.put(store.getStoreName(), store.getStoreCode());
            });
            // 遍历每个工作表
            for (int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++) {
                String sheetName = workbook.getSheetAt(sheetIndex).getSheetName();
                // 数据列表
                List<XsOrderRefundImportDto> importDtoList = util.importExcel(sheetName, file.getInputStream(), 0);

                if (StringUtils.isNotEmpty(importDtoList)) {
                    for (XsOrderRefundImportDto importDto : importDtoList) {

                        orderId = importDto.getAcookieId();
                        XsOrderRefund orderRefund = new XsOrderRefund();

                        BeanUtil.copyProperties(importDto, orderRefund);


                        if (StringUtils.isNotEmpty(orderRefundList)) {
                            Set<String> orderIdList = orderRefundList.stream().map(XsOrderRefund::getAcookieId)
                                    .filter(id -> id != null && !id.isEmpty())
                                    .collect(Collectors.toSet());

                            if (orderIdList.contains(orderRefund.getAcookieId())) {
                                orderRefundList.stream()
                                        .filter(o -> Objects.equals(o.getAcookieId(), importDto.getAcookieId()))
                                        .findFirst().ifPresent(existingOrder -> {
                                            orderRefund.setId(existingOrder.getId());
                                            exist.add(orderRefund);
                                        });
                            } else {
                                orderRefund.setCreateBy(SecurityUtils.getUserId().toString());
                                orderRefund.setCreateTime(DateUtils.getNowDate());
                                nonentity.add(orderRefund);
                            }
                        } else {
                            orderRefund.setCreateBy(SecurityUtils.getUserId().toString());
                            orderRefund.setCreateTime(DateUtils.getNowDate());
                            nonentity.add(orderRefund);
                        }
                        count++;
                    }
                }
//                else {
//                    throw new GlobalException("导入失败！excel第" + sheetIndex + 1 + "个工作表内数据为空");
//                }
            }
            taskExecutor.submit(() -> {
                try {
                    if (StringUtils.isNotEmpty(exist)) {
                        this.updateBatchById(exist);
                    }
                    if (StringUtils.isNotEmpty(nonentity)) {
                        this.saveBatch(nonentity);
                    }
                } catch (Exception e) {
                    System.out.println("失败！" + e);
                }finally {
                    System.out.println("结束");
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
            throw new GlobalException("文件读取错误");
        } catch (Exception e) {
            throw new RuntimeException(e + "--" + count + "---" + orderId);
        }
    }
}
